<template>
  <BreadcrumbBar
    parent-label="Authority Management"
    child-label="System Management"
  ></BreadcrumbBar>

  <InputForm>
    <InputItem label="查询系统信息" more-long="500">
      <el-select
        v-model="querySystemCode"
        placeholder="Select"
        clearable
        size="large"
      >
        <el-option
          v-for="item in rootSystemOption"
          :key="item.label"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </InputItem>

    <ButtomItem label="操作">
      <el-button
        style="height: 100%"
        v-once-click
        color="#626aef"
        plain
        @click="getSystemInfoList"
      >
        查询
      </el-button>

      <el-button
        style="height: 100%"
        v-once-click
        color="#626aef"
        plain
        @click="openCreateSystemInfoDialog"
      >
        新建系统信息
      </el-button>

      <el-button
        style="height: 100%"
        v-once-click
        color="#626aef"
        plain
        @click="openRootSystemListDialog"
      >
        根系统列表
      </el-button>

      <el-button
        style="height: 100%"
        v-once-click
        color="#626aef"
        plain
        @click="openAddSystemDialog"
      >
        新增根系统
      </el-button>

      <DesensitizeDataVerify
        @success-handler="getSystemInfoList"
      ></DesensitizeDataVerify>
    </ButtomItem>
  </InputForm>

  <!-- 系统信息表格 -->
  <TableCard
    operationBarLabel="批量操作系统信息"
    :show-expand="50"
    :table-max-height="450"
  >
    <template #operationBar>
      <el-button
        v-once-click
        color="#626aef"
        plain
        size="small"
        @click="updateSystemInfoStatus(multipleSelectionItems, 0)"
      >
        启用
      </el-button>
      <el-button
        v-once-click
        type="info"
        size="small"
        @click="updateSystemInfoStatus(multipleSelectionItems, 1)"
      >
        禁用
      </el-button>
      <el-popconfirm
        title="确认删除"
        placement="right"
        @confirm="deleteSystemInfo(multipleSelectionItems)"
      >
        <template #reference>
          <el-button v-once-click color="#F56C6C" plain size="small">
            删除
          </el-button>
        </template>
      </el-popconfirm>
    </template>

    <template #table="{ maxHeight }">
      <el-table
        :data="querySystemInfoList"
        stripe
        style="width: 100%"
        :max-height="maxHeight"
        @selection-change="handleSelectionChange"
        :headerCellStyle="tableHeaderCellStyle"
      >
        <el-table-column type="selection" width="30" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column property="enable" label="Enable" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.enable === 1" type="danger"> 禁用 </el-tag>
            <el-tag v-if="scope.row.enable === 0" type="success"> 启用 </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="systemCode" label="SystemCode" width="200" />
        <el-table-column
          property="systemName"
          label="SystemName"
          min-width="160"
        />
        <el-table-column property="systemIP" label="SystemIP" min-width="200" />
        <el-table-column property="remark" label="Remark" min-width="160" />
        <el-table-column
          property="createTime"
          label="CreateTime"
          sortable
          width="190"
        />
        <el-table-column
          property="updateTime"
          label="UpdateTime"
          sortable
          width="190"
        />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              v-once-click
              type="info"
              size="small"
              v-if="scope.row.enable === 0"
              @click="updateSystemInfoStatus([scope.row.id], 1)"
            >
              禁用
            </el-button>
            <el-button
              v-once-click
              color="#626aef"
              plain
              size="small"
              v-if="scope.row.enable === 1"
              @click="updateSystemInfoStatus([scope.row.id], 0)"
            >
              启用
            </el-button>
            <el-button
              v-once-click
              color="#E6A23C"
              plain
              size="small"
              @click="
                openUpdateSystemInfoDialog(
                  scope.row.id,
                  scope.row.systemCode,
                  scope.row.systemIP,
                  scope.row.remark
                )
              "
            >
              修改
            </el-button>
            <el-popconfirm
              title="确认删除"
              placement="left"
              @confirm="deleteSystemInfo([scope.row.id])"
            >
              <template #reference>
                <el-button v-once-click color="#F56C6C" plain size="small">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template #paginationBar>
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[20, 30, 40, 50, 60]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handlePageNumChange"
    /></template>
  </TableCard>

  <!--  -->
  <!-- 根系统列表 -->
  <el-dialog
    v-model="rootSystemListDialogVisible"
    title="根系统列表"
    width="900px"
    draggable
    align-center
    :before-close="closeRootSystemListDialog"
  >
    <el-table
      :data="rootSystemList"
      stripe
      style="width: 100%"
      :headerCellStyle="tableHeaderCellStyle"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column property="enable" label="Enable" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.enable === 1" type="danger"> 禁用 </el-tag>
          <el-tag v-if="scope.row.enable === 0" type="success"> 启用 </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        property="systemName"
        label="SystemName"
        min-width="160"
      />
      <el-table-column
        property="systemCode"
        label="SystemCode"
        min-width="200"
      />
      <el-table-column
        property="createTime"
        label="CreateTime"
        sortable
        width="190"
      />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button
            v-once-click
            type="info"
            size="small"
            v-if="scope.row.enable === 0"
            @click="enableSystem(scope.row.id, 1)"
          >
            禁用
          </el-button>
          <el-button
            v-once-click
            color="#626aef"
            plain
            size="small"
            v-if="scope.row.enable === 1"
            @click="enableSystem(scope.row.id, 0)"
          >
            启用
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <div>
        <el-button
          style="width: 120px"
          color="#626aef"
          plain
          @click="closeRootSystemListDialog"
        >
          关闭
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  -->
  <!-- 新增根系统对话框 -->
  <el-dialog
    v-model="addSystemDialogVisible"
    title="新增根系统对话框"
    width="800px"
    draggable
    :before-close="closeAddSystemDialog"
  >
    <InputForm>
      <InputItem label="新建系统">
        <el-input
          v-model="systemName"
          placeholder="请输入系统名称"
          maxlength="20"
          clearable
          show-word-limit
      /></InputItem>
      <InputItem label="系统编码">
        <el-input
          v-model="systemCode"
          placeholder="请输入系统编码"
          maxlength="30"
          clearable
          show-word-limit
      /></InputItem>
    </InputForm>

    <div class="tips">根系统创建后不能修改</div>

    <template #footer>
      <div>
        <el-button
          style="width: 120px"
          v-once-click
          color="#909399"
          plain
          @click="closeAddSystemDialog"
        >
          取消
        </el-button>
        <el-button
          style="width: 120px"
          v-once-click
          color="#626aef"
          @click="addRootSystem"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  -->
  <!-- 系统信息创建对话框 -->
  <el-dialog
    v-model="createSystemInfoDialogVisible"
    title="创建系统信息对话框"
    width="800px"
    draggable
    :before-close="closeSystemInfoDialog"
  >
    <InputForm>
      <InputItem label="系统信息分类">
        <el-select v-model="tempSystemCode" placeholder="Select" size="large">
          <el-option
            v-for="item in rootSystemOption"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          /> </el-select
      ></InputItem>
      <InputItem label="系统远程地址">
        <el-input
          v-model="systemIpAddress"
          placeholder="请输入系统IP地址"
          maxlength="20"
          show-word-limit
      /></InputItem>
      <InputItem label="备注">
        <el-input
          v-model="systemRemark"
          placeholder="请输入系统备注"
          maxlength="20"
          show-word-limit
      /></InputItem>
    </InputForm>

    <template #footer>
      <div>
        <el-button
          style="width: 120px"
          v-once-click
          color="#909399"
          plain
          @click="closeSystemInfoDialog"
        >
          取消
        </el-button>
        <el-button
          style="width: 120px"
          v-once-click
          color="#626aef"
          @click="createDialogConfirmHandler"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  -->
  <!-- 系统信息修改对话框 -->
  <el-dialog
    v-model="updateSystemInfoDialogVisible"
    title="修改系统信息对话框"
    width="800px"
    draggable
    :before-close="closeSystemInfoDialog"
  >
    <InputForm>
      <InputItem label="系统信息分类">
        <el-select
          v-model="tempSystemCode"
          placeholder="Select"
          size="large"
          disabled
        >
          <el-option
            v-for="item in rootSystemOption"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          /> </el-select
      ></InputItem>
      <InputItem label="系统远程地址">
        <el-input
          v-model="systemIpAddress"
          placeholder="请输入系统IP地址"
          maxlength="20"
          show-word-limit
      /></InputItem>
      <InputItem label="备注">
        <el-input
          v-model="systemRemark"
          placeholder="请输入系统备注"
          maxlength="20"
          show-word-limit
      /></InputItem>
    </InputForm>

    <template #footer>
      <div>
        <el-button
          style="width: 120px"
          v-once-click
          color="#909399"
          plain
          @click="closeSystemInfoDialog"
        >
          取消
        </el-button>
        <el-button
          style="width: 120px"
          v-once-click
          color="#626aef"
          @click="updateDialogConfirmHandler"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { storeToRefs } from 'pinia'
import {
  useSortTreeStore,
  useThemeStore,
  useDesensitizeVerifyStore,
} from '@/features/store/store'
import { useMessageAlertStore } from '@/features/store/componentStore'
import {
  getSystemInfoListApi,
  setSystemInfoApi,
  deleteSystemInfoApi,
  updateSystemInfoStatusAPi,
} from '@/request/api/systemInfo'
import {
  addRootSystemApi,
  getRootSystemApi,
  enableSystemApi,
} from '@/request/api/rootSystem'

import DesensitizeDataVerify from '@/components/DesensitizeDataVerify/DesensitizeDataVerify.vue'
import InputForm from '@/components/InputForm/InputForm.vue'
import InputItem from '@/components/InputForm/InputItem.vue'
import ButtomItem from '@/components/InputForm/ButtomItem.vue'
import TableCard from '@/components/TableCard/TableCard.vue'
import BreadcrumbBar from '@/components/BreadcrumbBar/BreadcrumbBar.vue'

const { originData } = storeToRefs(useSortTreeStore())
const { getSortList } = useSortTreeStore()

const { openAlert } = useMessageAlertStore()

const { tableHeaderCellStyle } = useThemeStore()
const { judgeExpireTime } = useDesensitizeVerifyStore()

onMounted(() => {
  getRootSystem()
  getSystemInfoList()
  if (originData.value.length === 0) getSortList()
  let l = []
  originData.value.map((item) => {
    if (item.level === 1) l.push({ label: item.description, value: item.id })
  })
})

// 根系统信息列表
const rootSystemList = ref<RootSystem.RootSystemItf[]>([])
// 根系统信息项
const rootSystemOption = ref<any[]>([])
const rootSystemListDialogVisible = ref(false)

const openRootSystemListDialog = () => {
  rootSystemListDialogVisible.value = true
}
const closeRootSystemListDialog = () => {
  rootSystemListDialogVisible.value = false
}

// 获取所有根系统列表
const getRootSystem = async () => {
  const res = await getRootSystemApi()
  if (res.code !== 200) return openAlert.error(res.message)
  rootSystemList.value = res.data

  rootSystemOption.value = res.data.map((item) => {
    return { label: item.systemName, value: item.systemCode }
  })
}

const systemName = ref<string>('')
const systemCode = ref<string>('')
const addSystemDialogVisible = ref(false)

const openAddSystemDialog = () => {
  addSystemDialogVisible.value = true
}
const closeAddSystemDialog = () => {
  addSystemDialogVisible.value = false
  systemName.value = ''
  systemCode.value = ''
}

//创建根系统
const addRootSystem = async () => {
  if (systemName.value.length === 0)
    return openAlert.warning('分类上级不能为空！')
  if (systemCode.value.length === 0)
    return openAlert.warning('分类上级不能为空！')

  const res = await addRootSystemApi({
    systemName: systemName.value,
    systemCode: systemCode.value,
  })
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('创建成功！')
  getRootSystem()
  closeAddSystemDialog()
  useSortTreeStore().getSortList()
}

// 批量启用或禁用根系统
const enableSystem = async (id: number, enable: 0 | 1) => {
  const res = await enableSystemApi([id], enable)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('设置状态成功')
  getRootSystem()
  getSystemInfoList()
  useSortTreeStore().getSortList()
}

const total = ref<number>(0)
const pageNum = ref<number>(1)
const pageSize = ref<number>(20)
const handlePageNumChange = (val: number) => {
  pageNum.value = val
  getSystemInfoList()
}
const handlePageSizeChange = (val: number) => {
  pageSize.value = val
  getSystemInfoList()
}

// 系统信息分类id
const querySystemCode = ref<string>('')
// 查询到的系统信息列表
const querySystemInfoList = ref<SystemInfoItf[]>([])
// 获取系统信息列表
const getSystemInfoList = async () => {
  const res = await getSystemInfoListApi(
    pageNum.value,
    pageSize.value,
    querySystemCode.value || ''
  )
  if (res.code !== 200) return openAlert.error(res.message)
  // ElMessage.success('查询系统信息成功')
  querySystemInfoList.value = res.data.records
  total.value = res.data.total
}

// 当前系统信息id
const currentSystemInfoId = ref<string>('')
// 系统 ip 地址
const systemIpAddress = ref<string>('')
// 备注
const systemRemark = ref<string>('')
// 创建，修改权限时的分类id
const tempSystemCode = ref<string>('')

// 创建系统信息对话框
const createSystemInfoDialogVisible = ref(false)
// 修改系统信息对话框
const updateSystemInfoDialogVisible = ref(false)

const openCreateSystemInfoDialog = () => {
  createSystemInfoDialogVisible.value = true
}
const openUpdateSystemInfoDialog = async (
  id: string,
  systemCode: string,
  systemIP: string,
  remark: string
) => {
  const sta = await judgeExpireTime()
  if (sta === false) return openAlert.error('请先进行脱敏校验认证')

  currentSystemInfoId.value = id
  systemIpAddress.value = systemIP
  tempSystemCode.value = systemCode
  systemRemark.value = remark
  updateSystemInfoDialogVisible.value = true
}
const closeSystemInfoDialog = () => {
  createSystemInfoDialogVisible.value = false
  updateSystemInfoDialogVisible.value = false
  systemIpAddress.value = ''
  currentSystemInfoId.value = ''
  tempSystemCode.value = ''
  systemRemark.value = ''
}
const createDialogConfirmHandler = () => {
  createSystemInfo()
  closeSystemInfoDialog()
}
const updateDialogConfirmHandler = () => {
  updateSystemInfo()
  closeSystemInfoDialog()
}

// 创建系统信息
const createSystemInfo = async () => {
  const res = await setSystemInfoApi({
    systemIP: systemIpAddress.value,
    systemCode: tempSystemCode.value,
    remark: systemRemark.value,
  })
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('系统信息创建成功！')
  getSystemInfoList()
}

// 修改系统信息
const updateSystemInfo = async () => {
  const res = await setSystemInfoApi({
    systemIP: systemIpAddress.value,
    systemCode: tempSystemCode.value,
    id: currentSystemInfoId.value,
    remark: systemRemark.value,
  })
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('系统信息修改成功！')
  getSystemInfoList()
}

// 多选系统信息选项
const multipleSelectionItems = ref<string[]>([])
const handleSelectionChange = (val: PermissionItf[]) => {
  let ids: string[] = []
  for (let item of val) ids.push(item.id)
  multipleSelectionItems.value = ids
}

// 批量删除系统信息
const deleteSystemInfo = async (ids: string[]) => {
  const res = await deleteSystemInfoApi(ids)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('系统信息删除成功！')
  getSystemInfoList()
}

// 批量更新系统信息状态
const updateSystemInfoStatus = async (ids: string[], status: 0 | 1) => {
  const res = await updateSystemInfoStatusAPi(ids, status)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('系统信息状态更新成功！')
  getSystemInfoList()
}
</script>

<style lang="less" scoped>
.tips {
  font-size: 14px;
  font-weight: bold;
  color: #918f8f;
  padding: 10px 10px;
}
</style>
